package com.hawk.aspect;

import cn.hutool.core.util.StrUtil;
import com.hawk.annotation.LogNote;
import com.hawk.domain.LogDomain;
import com.hawk.parse.*;
import com.hawk.utils.ExpressionUtils;
import com.hawk.utils.HttpUtil;
import com.hawk.utils.SpringContextUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * @author hawk
 * @date 2022/1/10 15:12
 * @desc
 **/
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = Logger.getLogger("com.hawk.aspect.LogAspect");

    @Autowired
    private LogUserService logUserService;
    @Autowired
    private LogPrintService logPrintService;

    @Pointcut("@annotation(com.hawk.annotation.LogNote)")
    public void logNote() {

    }

    @Around("logNote()")
    public Object aroundLogNote(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogNote logNote = method.getAnnotation(LogNote.class);
        //不可能出现这种情况
        assert logNote != null;
        try {
            //执行业务逻辑
            Object proceed = joinPoint.proceed();
            //生成完整上下文
            LogEvaluationContext context = new LogEvaluationContext(
                    new Object(), method, joinPoint.getArgs(), new DefaultParameterNameDiscoverer());

            //操作日志解析
            String operate = logNote.operate();
            String[] operateParam = logNote.operateParam();
            for (int i = 0; i < operateParam.length; i++) {
                String paramValue = ExpressionUtils.getExpressionValue(context, operateParam[i]);
                operate = operate.replace("{" + (i + 1) + "}", paramValue);
            }
            //自定义方法解析
            //解析自定义方法所需参数
            List<String> funcParam = parseFuncParam(operate);
            String[] functions = logNote.functions();
            for (int i = 0; i < functions.length; i++) {
                //根据方法名获取到对应的bean
                IFunction f = (IFunction) SpringContextUtil.getBean(functions[i]);
                String param = funcParam.get(i);
                //获取最终值
                String rs = f.apply(param);
                operate = operate.replaceFirst("func\\(\\w+\\)", rs);
            }

            //操作资源解析
            String resourceNo = ExpressionUtils.getExpressionValue(context, logNote.resource());
            //封装日志完整信息
            LogDomain logDomain = LogDomain.builder()
                    .ip(HttpUtil.getIpAddress(request))
                    .user(logUserService.getUser())
                    .methodName(method.getName())
                    .args(joinPoint.getArgs())
                    .operate(operate)
                    .resourceNo(String.valueOf(resourceNo))
                    .category(logNote.category())
                    .remark(logNote.remark())
                    .build();
            //打印日志格式化信息
            logPrintService.print(logDomain);
            //执行成功
            return proceed;
        } catch (Throwable e) {
            logger.severe("执行失败, " + e.getMessage());
            throw new Throwable(e.getMessage());
        } finally {
            LogParser.remove();
        }
    }

    /**
     * 解析字符串中的自定义方法参数
     *
     * @param operate
     * @return
     */
    private List<String> parseFuncParam(String operate) {
        List<String> params = new ArrayList<>();
        String[] group = operate.split("func");
        for (String st : group) {
            if (!st.startsWith("(")) {
                continue;
            }
            if (StrUtil.isEmpty(st)) {
                continue;
            }
            char[] chars = st.toCharArray();
            StringBuilder result = new StringBuilder();
            for (char c : chars) {
                if (c == '(') {
                    continue;
                }
                if (c == ')') {
                    break;
                }
                result.append(c);
            }
            params.add(result.toString());
        }
        return params;
    }
}
